package com.ourcraft.informationcollectionsystem.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.Company;
import com.ourcraft.informationcollectionsystem.entity.DataReportForm;
import com.ourcraft.informationcollectionsystem.entity.User;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import com.ourcraft.informationcollectionsystem.service.common.addQueryHistory.AddHistoryService;
import com.ourcraft.informationcollectionsystem.service.company.companyInfomation.CompanyInformationService;
import com.ourcraft.informationcollectionsystem.service.company.fillingFormInfo.FillingFormInfoService;
import com.ourcraft.informationcollectionsystem.utils.authority.AuthorityCode;
import com.ourcraft.informationcollectionsystem.utils.authority.AuthorityValidator;
import com.ourcraft.informationcollectionsystem.utils.response.Result;
import com.ourcraft.informationcollectionsystem.utils.response.ResultCode;
import com.ourcraft.informationcollectionsystem.utils.statusCode.HistoryType;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DataFillingController handles Enterprise-Data-Filling-related operations.
 *
 * @author Xiong Keqin
 * @since 2023-11-04
 */
@RequestMapping("enterprise/dataFilling/")
@RestController
@CrossOrigin
@AuthorityValidator(code = AuthorityCode.DATA_FORM_SUBMIT)
public class DataFillingController {

    @Autowired
    FillingFormInfoService fillingFormInfoService;

    @Autowired
    CompanyInformationService companyInformationService;

    @Autowired
    AddHistoryService addHistoryService;

    /**
     * Retrieves information of list of forms to be filled out by user ID.
     *
     * @param userId The ID of the user.
     * @param request Permission verification related.
     * @return information of list of forms to be filled out.
     */
    @GetMapping("allFillingDataInfo")
    public Result<List<Map<String, Object>>> getAllFillingDataInfo(@RequestParam int userId, HttpServletRequest request) {
        Integer cId = companyInformationService.user2CompanyId(userId);
        List<Map<String, Object>> data = fillingFormInfoService.getAllFillingDataInfo(cId);
        return Result.success(data);
    }

    /**
     * Retrieves information of form to be filled out by form ID.
     *
     * @param formID The ID of the form.
     * @param request Permission verification related.
     * @return information of form to be filled out.
     */
    @GetMapping("fillingFormInfo")
    public Result<Map<String, Object>> getFillingFormInfo(@RequestParam int formID, HttpServletRequest request) {
        // 创建一个新的Map
        Map<String, Object> data = new HashMap<>();
        DataReportForm dataReportForm = fillingFormInfoService.getFillingFormInfo(formID);
        if(dataReportForm != null){
            data.put("formID", dataReportForm.getFormId());
            data.put("companyID", dataReportForm.getCompanyId());
            data.put("formInvestigationID", dataReportForm.getInvestigationId());
            data.put("formStartTotalNum", dataReportForm.getFormStartTotalNum());
            data.put("formEndTotalNum", dataReportForm.getFormEndTotalNum());
            data.put("formDecreaseType", dataReportForm.getFormDecreaseType());
            data.put("formFirstReason", dataReportForm.getFormFirstReason());
            data.put("formSecondReason", dataReportForm.getFormSecondReason());
            data.put("formThirdReason", dataReportForm.getFormThirdReason());
            data.put("formReasonDescription", dataReportForm.getFormReasonDescription());
            data.put("formExamineStatus", dataReportForm.getFormExamineStatus());

            Company company = companyInformationService.getCompanyInfo2(dataReportForm.getCompanyId());
            data.put("companyChineseName", company.getCompanyChineseName());
        }
        else{
            Result.fail();
        }
        return Result.success(data);
    }

    /**
     * Update form information.
     *
     * @param param The form information.
     * @param request Permission verification related.
     * @return Operation result.
     */
    @PostMapping("submitFillingFormInfo")
    public Result<String> submitFillingFormInfo(@RequestBody JSONObject param, HttpServletRequest request) {
        // 创建一个新的Map
//        System.out.println("\n\n submitFillingFormInfo:");
//        System.out.println(param.toString());
        Map<String, Object> data = new HashMap<>();
        DataReportForm da1 = new DataReportForm(param);

        Boolean str0 = fillingFormInfoService.submitFillingFormInfo(da1, param.getBoolean("is_Submit"));

        if(str0 != null){
            if (param.getBoolean("is_Submit")) {
                addHistoryService.addFormSubmission(
                        da1.getFormId(),
                        getCompanyIdByFormId(da1.getFormId()),
                        HistoryType.COMPANY_SUBMIT.ordinal(),
                        "",
                        true
                );
            };
            return Result.success();
        }
        return Result.fail(ResultCode.FAIL,"Failed");
    }

    @Autowired
    DataReportFormMapper dataReportFormMapper;

    // 根据FormId找userId
    private int getCompanyIdByFormId(int formId) {
        QueryWrapper<DataReportForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", formId);
        return dataReportFormMapper.selectOne(queryWrapper).getCompanyId();
    }

    @GetMapping("testConnection")
    public Result<User> testConnection() {
        return Result.success();
    }
}
